package com.abl.core.common.security;

import com.abl.core.common.cache.Cache;
import com.abl.core.common.util.AuthKit;
import com.abl.core.domain.project.MSG;
import com.abl.core.domain.project.ServiceException;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 表参参数重复提交校验
 */
@Aspect
@Component
@Slf4j
public class ReSubmitHandler {

    @Resource
    private Cache<String> cache;


    @Before("@annotation(reSubmit)")
    public void interceptor(ReSubmit reSubmit) {
        String validKEY = createValidKEY(reSubmit.hasLogin());

        Long count = cache.incr(validKEY, reSubmit.expire());

        //重复提
        if (count.intValue() > 0) throw new ServiceException(MSG.RE_SUBMIT);

    }

    /**
     * 生成唯一请求标记
     *
     * @param hasLogin 是否需要登录
     * @return 唯一请求标记
     */
    private String createValidKEY(Boolean hasLogin) {
        StringBuilder stringBuilder = new StringBuilder();

        //必须登录后使用
        if (hasLogin) {
            AuthUser authUser = AuthKit.mastLogin();
            stringBuilder.append(authUser.getUserId());
        }

        //追加请求地址和请求参数
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        stringBuilder.append(request.getRequestURI());
        if (!request.getParameterMap().isEmpty()) {
            stringBuilder.append(JSONObject.toJSONString(request.getParameterMap()));
        }

        //返回KEY标记
        return stringBuilder.toString();
    }


}
